<template>
  <el-upload
    ref="uploadRef"
    :accept="props.accept"
    :http-request="uploadRequest"
    :before-upload="onBeforeUpload"
    :on-remove="handleRemove"
    :limit="props.limit"
  >
    <template #trigger>
      <slot><el-button > {{ props.label }} </el-button></slot>
    </template>
  </el-upload>
</template>
<script lang="ts" setup>
import { ref, defineProps, defineEmits, withDefaults } from 'vue'
import { UploadInstance, ElMessage } from 'element-plus'

import { doUploadFile } from '@renderer/ajax/api/common'

const emit = defineEmits<{
  (event: 'handleUploaded', fileInfo: { file_name:string, url: string  }): void
  (event: 'handleUploadRemove', file:any): void
}>()
const props = withDefaults(defineProps<{
  fileSize?: string | number,
  accept?: string,
  label?: string,
  limit?: number
}>(), {
  limit: 1,
  label: '上传文件'
})

const uploadRef:any = ref<UploadInstance>()

// 上传前校验
const onBeforeUpload = (rawFile:any) => {
  console.log('rawFile: ', rawFile);
  const _file = rawFile;
  const fileSize = Number(props.fileSize)
  console.log('fileSize: ', fileSize);
  if (fileSize) {
    const isLt2M = _file.size / 1024 / 1024 < fileSize;
    if (!isLt2M) {
      ElMessage.error(`请上传${fileSize}M以下的.xlsx文件`)
      return false;
    }
  }

  if (props.accept) {
    // 校验文件类型
    const file_type: any = _file.name.split('.')
    console.log(props.accept, file_type);
    if (!props.accept.includes(file_type[file_type.length - 1])) {
      ElMessage.error(`请上传${props.accept}格式的文件`)
      return false
    }
  }
  
  return true
}
// 自定义上传
const uploadRequest = async (options: any) => {
  const formData = {
    file: options.file,
    file_name: options.file.name
  }
  doUploadFile(formData).then(async (res: any) => {
    options.file.url = res.url
    emit('handleUploaded', { file_name: formData.file_name, url: res.url })
  }).catch(() => {
    uploadRef.value.handleRemove(options)
  })
}

const handleRemove = async (uploadFile:any, uploadFiles:any) => {
  emit('handleUploadRemove', uploadFile)
}

</script>

<style lang="scss" scoped >
  :deep(.el-button) {
    background-color: var(--btn-file-bgcolor);
    border: var(--border-normal);
  }
</style>